package middle;

import java.util.LinkedList;

public class Solution_116 {
    public Node connect(Node root) {
        if (root != null && root.left != null && root.right != null) {
            connect(root.left);
            connect(root.right);
            dps(root.left, root.right);
        }
        return root;
    }

    private void dps(Node left, Node right) {
        left.next = right;
        if (left.right != null && right.left != null) {
            dps(left.right, right.left);
        }
    }

    public static void main(String[] args) {
        Solution_116 model = new Solution_116();
        Node node = new Node(1);
        node.left = new Node(2);
        node.left.left = new Node(4);
        node.left.right = new Node(5);
        node.right = new Node(3);
        node.right.left = new Node(6);
        node.right.right = new Node(7);
        Node root = model.connect(node);
        System.out.println();
    }

    public Node connect1(Node root) {
        if (root == null) {
            return null;
        }
        LinkedList<Node> list = new LinkedList<>();
        list.add(root);
        while (!list.isEmpty()) {
            Node pre = null;
            int count = list.size();
            for (int i = 0; i < count; i++) {
                Node node = list.pop();
                if (node.left != null) {
                    list.add(node.left);
                }
                if (node.right != null) {
                    list.add(node.right);
                }
                if (pre != null) {
                    pre.next = node;
                }
                pre = node;
            }
        }
        return root;
    }

    static class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }
}
